import { Component, OnInit } from '@angular/core';
import { Router,ActivatedRoute } from '@angular/router';

import { HttpClient } from '@angular/common/http';

interface FormInfo{
  id:number,
  name:string,
  email:string,
  phone:string
}

@Component({
  selector: 'app-contact-edit',
  templateUrl: './contact-edit.component.html',
  styleUrls: ['./contact-edit.component.less']
})
export class ContactEditComponent implements OnInit {

  public formData:FormInfo = {
    id:-1,
    name:'',
    email:'',
    phone:''
  };

  constructor(
    private router:Router,
    private route:ActivatedRoute
    private http:HttpClient
  ) { }

  ngOnInit() {
    let id = this.route.snapshot.params.id;
    this.getContactsById(id);
  }


  getContactsById(id){
    this.http.get(`http://localhost:3000/contacts/${id}`)
      .toPromise()
      .then((data:any)=>{
        this.formData = {
          id:data.id,
          name:data.name,
          email:data.email,
          phone:data.phone
        };
      })
      .catch(err => {
        alert('error');
      })
  }

  submitHandle(){
    let { id } = this.formData;
    this.http.patch('http://localhost:3000/contacts/' + id,this.formData)
      .toPromise()
      .then((res)=>{
        this.router.navigate(['/contacts'])
      })
      .catch(err=>{
        alert('error')
      })
  }

}
